package com.leyou.search.service.impl;

import com.leyou.common.dto.PageDTO;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.search.entity.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.IndexService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndexServiceImpl implements IndexService {
    //访问item获取spu
    @Autowired
    private ItemClient itemClient;

    @Autowired
    private GoodsRepository goodsRepository;


    @Override
    public void loadData(){
        DeleteAndCreate();
        //对商品spu查询
        int page=1;
        while (true){
            PageDTO<SpuDTO> pageDTO = this.itemClient.querySpuByPage(page, 50, true, null, null, null);
            //没有数据
            if (pageDTO.getTotalPage()==0){
                break;
            }
            List<Goods> goodsList = pageDTO.getItems()
                    .stream().map(this::buildGoods)
                    .collect(Collectors.toList());
            //批量保存索引库
            this.goodsRepository.saveAll(goodsList);

            page++;

            if (pageDTO.getTotalPage()<page){
                break;
            }


        }

    }
    //查询出的spudto转换为goods
    @Override
    public Goods buildGoods (SpuDTO spuDTO){
        Goods goods = new Goods();

        BeanUtils.copyProperties(spuDTO,goods);

        //suggestion 品牌+分类 品牌+主题 分类+品牌
        List<String> suggestion=new ArrayList<>();
        String brandName=StringUtils.substringBefore(spuDTO.getBrandName(),"（");
        String name = spuDTO.getName();
        String categoryName=spuDTO.getCategoryName().split("/")[2];
//        String BCName=brandName+spuDTO.getCategoryName().split("/")[2];
//        String BName=brandName+spuDTO.getName();
//        String CBName=spuDTO.getCategoryName().split("/")[2]+brandName;
        suggestion.add(name);
        suggestion.add(name.startsWith(brandName)?brandName:brandName+name);
        suggestion.add(brandName+categoryName);
        suggestion.add(categoryName+brandName);
//        suggestion.add(BName);
        goods.setSuggestion(suggestion);
       //categoryid
        goods.setCategoryId(spuDTO.getCid3());

        //specs
        List<Map<String,Object>> speclist=this.itemClient.querySpecsValues(spuDTO.getId(),true).stream().map(specParamDTO -> {
            Map<String,Object>map=new HashMap<>();
            map.put("name",specParamDTO.getName());
            map.put("value",chooseSegment(specParamDTO));
            return map;
        }).collect(Collectors.toList());
        goods.setSpecs(speclist);

        //prices
        List<SkuDTO> skuDTOS = itemClient.querySkuBySpuId(spuDTO.getId());
        Set<Long> prices=new HashSet<>();
        Long sold=0l;
        //取出所有sku价格
        for (SkuDTO skuDTO : skuDTOS) {
            prices.add(skuDTO.getPrice()) ;
             sold += skuDTO.getSold();
        }
        //sold
        goods.setPrices(prices);

        goods.setSold(sold);

        //TITLE
        goods.setTitle(name+" "+brandName+" "+categoryName);
        //image
        goods.setImage(StringUtils.substringBefore(skuDTOS.get(0).getImages(),","));
        //updatetime
        goods.setUpdateTime(new Date());

        return goods;
    }
    public void DeleteAndCreate(){
        //删除索引库
        try {
            this.goodsRepository.deleteIndex();
        } catch (Exception e) {
        }

        this.goodsRepository.createIndex("{\n" +
                "  \"settings\": {\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"my_pinyin\": {\n" +
                "          \"tokenizer\": \"ik_smart\",\n" +
                "          \"filter\": [\n" +
                "            \"py\"\n" +
                "          ]\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "\t\t  \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": true,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": true\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"suggestion\": {\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"updateTime\":{\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"specs\":{\n" +
                "        \"type\": \"nested\",\n" +
                "        \"properties\": {\n" +
                "          \"name\":{\"type\": \"keyword\" },\n" +
                "          \"value\":{\"type\": \"keyword\" }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");
    }
    private Object chooseSegment(SpecParamDTO specParamDTO) {
        Object value = specParamDTO.getValue();
        if (value==null||StringUtils.isBlank(value.toString())){
            return "其他";
        }
        if (!specParamDTO.getNumeric()||StringUtils
                .isBlank(specParamDTO.getSegments())||value instanceof Collection){
            return  value;
        }
        double val=parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : specParamDTO.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + specParamDTO.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + specParamDTO.getUnit() + "以下";
                } else {
                    result = segment + specParamDTO.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str){
        try {
            return Double.parseDouble(str);
        } catch (NumberFormatException e) {
            return 0;
        }
    }



    @Override
    public void deleteGoodsById(Long spuId) {
        goodsRepository.deleteById(spuId);
    }

    @Override
    public void saveGoodsById(Long id) {
        //根据spuId做查询
        PageDTO<SpuDTO> spuDTOPageDTO =
                this.itemClient.querySpuByPage(1, 1, true, null, null, id);

        //如果查询到了
        if (1 == spuDTOPageDTO.getTotal()) {
            //把查询到的spuDTO取出转换为goods并保存
            SpuDTO spuDTO = spuDTOPageDTO.getItems().get(0);
            this.goodsRepository.save(buildGoods(spuDTO));
        }
    }
}
